package com.googlecode.lookie.swing.tree.samples;

import java.awt.BorderLayout;
import java.io.File;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;

import com.googlecode.lookie.swing.tree.model.DeferredTreeNode;
import com.googlecode.lookie.swing.tree.model.LazyTreeNodeModel;
import com.googlecode.lookie.swing.tree.model.util.DeferredTreeNodeWillExpandListener;
import com.googlecode.lookie.swing.tree.render.LabelProviderTreeCellRenderer;
import com.googlecode.lookie.swing.tree.support.file.FileTreeNode;
import com.googlecode.lookie.swing.tree.support.file.FileTreeNodeLabelProvider;
import com.googlecode.lookie.swing.tree.support.file.FileTreeNodeProvider;

public class DeferredTreeNodeSample
{

    private DeferredTreeNodeSample()
    {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

        FileSystemTreeNode root = new FileSystemTreeNode( null, null );
        FileSystemTreeNodeProvider provider = new FileSystemTreeNodeProvider();
        FileTreeNodeLabelProvider labelProvider = new FileTreeNodeLabelProvider();
        LazyTreeNodeModel model = new LazyTreeNodeModel( root, provider );
        LabelProviderTreeCellRenderer renderer = new LabelProviderTreeCellRenderer( labelProvider );

        JTree tree = new JTree( model );
        tree.setRootVisible( false );
        tree.setShowsRootHandles( true );

        tree.addTreeWillExpandListener( new DeferredTreeNodeWillExpandListener( new FileSystemTreeNodeProvider() ) );
        tree.setCellRenderer( renderer );
        JScrollPane scrollPane = new JScrollPane( tree );
        frame.getContentPane().add( scrollPane, BorderLayout.CENTER );

        frame.pack();
        frame.setVisible( true );
    }

    private class FileSystemTreeNodeProvider
        extends FileTreeNodeProvider
    {

        @Override
        protected TreeNode createTreeNode( File file, TreeNode parent )
        {
            try
            {
                Thread.sleep( 20 );
            }
            catch ( InterruptedException e )
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return new FileSystemTreeNode( file, parent );
        }

    }

    private class FileSystemTreeNode
        extends DeferredTreeNode
        implements FileTreeNode
    {

        private File file;

        public FileSystemTreeNode( File file, TreeNode parent )
        {
            super( parent );
            this.file = file;
        }

        public File getFile()
        {
            return file;
        }

    }

    public static void main( String[] args )
    {
        new DeferredTreeNodeSample();
    }

}
